#include "BasicFunc.h"
#include  <direct.h> 

void SecToDate(__int64 nSec, int*Y, int*M, int*D, int*h, int*m, int*s)
{
	if(Y) *Y = 0;
	if(M) *M = 0;
	if(D) *D = 0;
	if(h) *h = 0;
	if(m) *m = 0;
	if(s) *s = 0;

	struct tm *tm_s = localtime((time_t *)&nSec);
	if (tm_s == NULL)
		return;

	if(Y) *Y = tm_s->tm_year + 1900;
	if(M) *M = tm_s->tm_mon + 1;
	if(D) *D = tm_s->tm_mday;
	if(h) *h = tm_s->tm_hour;
	if(m) *m = tm_s->tm_min;
	if(s) *s = tm_s->tm_sec;
}


bool CLOG_FILE::DateLogFileOpen(char *pFileName, const char *mode)
{
	if(pFileName == NULL)
		return NULL;

	_mkdir("./log");
	static char tmpBuf[256] = {0};
	int y = 0, m = 0, d = 0;
	SecToDate(GET_TIME_I64(), &y, &m, &d);
	strncpy(m_FileName, pFileName, sizeof(m_FileName));
	strncpy(m_FileMode, mode, sizeof(m_FileMode));
	_snprintf(tmpBuf, sizeof(tmpBuf), "./log/%s_%d_%d_%d.txt", m_FileName, y, m, d);	
	m_nNowDay = d;	//rembmer days.
	m_fp = fopen(tmpBuf, m_FileMode);
	return m_fp!=NULL;
}

bool CLOG_FILE::WriteLogWithDate(char *pStr)
{
	if(m_fp == NULL || pStr == NULL)
		return false;
	
	static char tmpBuf[32];
	int y = 0, m = 0, d = 0, h = 0, i = 0, s = 0;
	SecToDate(GET_TIME_I64(), &y, &m, &d, &h, &i, &s);

	if(m_nNowDay != d) {
		//change days.
		fclose(m_fp);
		DateLogFileOpen(m_FileName, m_FileMode);
	}

	sprintf(tmpBuf,"[%02d:%02d:%02d]\t",h, i, s);
	fwrite(tmpBuf, strlen(tmpBuf), 1, m_fp);
	fwrite(pStr, strlen(pStr), 1, m_fp);
	fputc('\n', m_fp);
	fflush(m_fp);
	return true;
}